import { type UserConfig, type ConfigEnv, loadEnv, defineConfig } from 'vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
import tailwindcss from 'tailwindcss'
import Icons from 'unplugin-icons/vite'
import IconsResovler from 'unplugin-icons/resolver'
import Components from 'unplugin-vue-components/vite'
import path from 'path'
import vue from '@vitejs/plugin-vue'

const pathSrc = path.resolve(__dirname, 'src')
// https://vite.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
	const env = loadEnv(mode, process.cwd())
	return {
		resolve: {
			alias: {
				'@': pathSrc,
			},
		},
		plugins: [
			vue(),
			env.VITE_MOCK_DEV_SERVER === 'true' ? mockDevServerPlugin() : null,
			createSvgIconsPlugin({
				iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
				symbolId: 'icon-[dir]-[name]',
			}),
			AutoImport({
				imports: ['vue'],
				eslintrc: {
					enabled: true,
					filepath: './.eslintrc-auto-import.json',
				},
				resolvers: [
					ElementPlusResolver({
						importStyle: 'sass',
					}),
					IconsResovler(),
				],
				vueTemplate: true,
				dts: path.resolve(pathSrc, 'types', 'auto-imports.d.ts'),
			}),
			Components({
				resolvers: [
					ElementPlusResolver({
						importStyle: 'sass',
					}),
					IconsResovler({
						enabledCollections: ['ep'],
					}),
				],
				dts: path.resolve(pathSrc, 'types', 'components.d.ts'),
			}),
			Icons({
				autoInstall: true,
			}),
		],
		css: {
			postcss: {
				plugins: [tailwindcss],
			},
			preprocessorOptions: {
				scss: {
					additionalData: `@use "@/styles/theme.scss" as *;`,
				},
			},
		},
		server: {
			host: '0.0.0.0',
			port: Number(env.VITE_APP_PORT),
			open: true,
			proxy: {
				[env.VITE_APP_BASE_API]: {
					target: env.VITE_APP_TARGET,
					changeOrigin: true,
					rewrite: (path) => path.replace(new RegExp(`^` + env.VITE_APP_BASE_API), ''),
				},
			},
		},
	}
})
